package com.noodles.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.noodles.mall.entity.Cart;
import com.noodles.mall.entity.Order;
import com.noodles.mall.entity.OrderItem;
import com.noodles.mall.mapper.OrderItemMapper;
import com.noodles.mall.service.ItemService;
import com.noodles.mall.service.OrderItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/** 订单-商品 **/
@Service
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {
    @Autowired
    ItemService itemService;

    /** 添加: 单个 **/
    public boolean insert(OrderItem orderItem){
        return super.save(orderItem);
    }

    /** 添加: 批量 **/
    public boolean insertBath(Order order, List<Cart> cartList){
        List<OrderItem> orderItemList =new ArrayList<>();
        cartList.forEach(cart -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cart, orderItem);
            orderItem.setOrderId(order.getId());
            orderItem.setSalePrice(cart.getItem().getSalePrice());
            orderItem.setTotalPrice(cart.getItem().getSalePrice().multiply(new BigDecimal(cart.getItemCount())));
            orderItemList.add(orderItem);
        });
        return super.saveBatch(orderItemList);
    }

    /** 查询列表: order_id **/
    public List<OrderItem> selectList(Integer orderId){
        List<OrderItem> list=super.list(new QueryWrapper<OrderItem>().lambda()
                .eq(OrderItem::getOrderId,orderId)
                .orderByDesc(OrderItem::getCreatedTime)
        );
        list.forEach(orderItem -> {
            orderItem.setItem(itemService.selectOne(orderItem.getItemId()));
        });
        return list;
    }

}
